package com.ming.study.redis.controller;

import com.ming.study.redis.dto.StringDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/string")
@Slf4j
public class StringController {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @RequestMapping("/set")
    public String setString(@RequestBody StringDto request) {
        try {
            ValueOperations<Object, Object> stringOperations = redisTemplate.opsForValue();
            stringOperations.set(request.getKey(), request.getValue());
        }catch (Exception e){
            log.error(e.toString());
            return "fail";
        }
        return "success";
    }

    @RequestMapping("/get")
    public String getString(@RequestBody StringDto request) {
        try {
            ValueOperations<Object, Object> stringOperations = redisTemplate.opsForValue();
            return Objects.requireNonNull(stringOperations.get(request.getKey())).toString();
        }catch (Exception e){
            log.error(e.toString());
            return "fail";
        }
    }
}
